package com.blq.snblib.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.TextView;

import com.blq.snblib.R;

/**
 * ================================================
 * 作者: SSNB
 * 日期: 2016/8/29
 * 描述:
 * 横向渐变色TextView
 * 默认从红--绿--蓝
 * ================================================
 */

public class GradientTextView extends TextView {
    private static final String TAG = "GradientTextView";

    private LinearGradient mGradient;
    private int[] mGradientColors;
    private boolean isGradientChanged=false;

    public GradientTextView(Context context) {
        this(context,null);
    }

    public GradientTextView(Context context, AttributeSet attrs) {
        super(context,attrs);
        init(context,attrs);
        init();
    }

    public GradientTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs,defStyle);
        init(context,attrs);
        init();
    }

    private void init(Context context,AttributeSet attrs) {
        setGradientColors(getResources().getIntArray(R.array.gradient_default));
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.gradient_item);
        int n = ta.getIndexCount();
        for (int i = 0 ; i < n ; i++ ){
            int attr = ta.getIndex(i);
            if (attr == R.styleable.gradient_item_snb_color) {
                int array = ta.getResourceId(R.styleable.gradient_item_snb_color, R.array.gradient_default);
                setGradientColors(getResources().getIntArray(array));
            }
        }
        ta.recycle();
    }


    private void init() {
        setWillNotDraw(false);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = getPaint();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            setLayerType(LAYER_TYPE_NONE,paint);
        }
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        if(mGradient==null||isGradientChanged){
//            paint.measureText()
            mGradient = new LinearGradient(0, 0, getWidth(), getMeasuredHeight(),
                    mGradientColors, null, Shader.TileMode.REPEAT);
            isGradientChanged=false;
        }
        paint.setShader(mGradient);
        super.onDraw(canvas);
    }

    /**
     * 设置从左到右渐变的颜色
     * @param mGradientColors 颜色数组
     *                        显示颜色按数组顺序从左到右渐变
     */
    public void setGradientColors(int[] mGradientColors){
        isGradientChanged=true;
        this.mGradientColors=mGradientColors;
        invalidate();
    }
    public int[] getGradientColors(){
        return mGradientColors;
    }
}


